#!/usr/bin/env node

var fs = require("fs");



console.log("Checking that jsrepository is valid json...");
var jsRepo = JSON.parse(fs.readFileSync(__dirname + "/jsrepository.json"));
console.log("Validating regexes...")
var count = 0;
for (var i in jsRepo) {
	var types = ["uri", "filecontent", "filename", "filecontentreplace"];
	for (var j in types) {
		for (var k in jsRepo[i].extractors[types[j]]) {
			try {
				var restring = jsRepo[i].extractors[types[j]][k];
				count++;
				if (types[j] == "filecontentreplace") {
					var ar = /^\/(.*[^\\])\/([^\/]+)\/$/.exec(restring);
					if (ar == null) {
						console.warn("RegExp error - should be on format \"/search/replacement/\"", i, types[j], k);
						process.exit(1);
					}
					restring = ar[1];
				}
				var r = new RegExp(restring);
				var cre = restring.replace(/\\\(/g, "").replace(/\(\?:/g, "").split("(")[1];
				if (i != "dont check" && types[j] !== "filecontentreplace" && (!cre || cre.indexOf("§§version§§") !== 0)) {
					throw new Error("First capture must be §§version§§ for " + i + ": " + restring);
				}


			} catch(e) {
				console.warn("RegExp error ", i, types[j], k);
				throw e;
			}
		}
	}  
}
console.log(count + " regexes validated.")


console.log("Checking that npmrepository is valid json...");
var npmData = fs.readFileSync(__dirname + "/npmrepository.json", "utf-8");
var npmRepo = JSON.parse(npmData);
var k = Object.keys(npmRepo).filter(component => npmRepo[component].vulnerabilities.some(v => !v.below))
if (k.length > 0) throw new Error('Components ' + k.map(c => '"' + c + '"').join(', ') + ' are missing "below"');

console.log("Looking for duplicate keys in npmrepo ...");
Object.keys(npmRepo).map(k => {
	if (npmData.split('"' + k + '"').length > 2) {
		throw new Error("Duplicate key for " + k);
	}
})

console.log("Success");
